package com.tabview.difficultpoint;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.xudow.app.R;

import java.util.ArrayList;
import java.util.List;


/**
 * @author sun
 *         本class与table_view_layout.xml布局连用，如需修改界面参数
 *         请阅览布局文件
 */

public class TabPagerView extends LinearLayout implements OnPageChangeListener, View.OnClickListener {
    private int mMaxHolCount;                // 容纳超过几个title时需要滚动
    private ViewPager mViewPager;            // 核心切换控件
    private FragmentActivity mActivity;        // 父活动引用，用来初始化ViewPagerApdater
    private List<Fragment> mFragmentList;    // fragment子页面缓存
    private int mSlideWidthSpace;            // 滑块Slide的活动空间宽度（实际宽度，不包括活动）
    private int mSlideWidthScroll;            // 超出3个子页面的时候滑块宽度，默认值
    private int mSlideWidth;                // 滑块宽度动态值
    private int mSlideHeight;                // 滑块的高度
    private ImageView mSlide;                // 滑块对象
    private LinearLayout mButtonLinear;        // 页选择按钮容器，用来根据滑动页面数量 addVIew 动态添加按钮
    private List<TextView> mButtonTitle;    // 按钮对象缓存
    private PagerAdapter mPageAdapter;        // viewPage 适配器
    private HorizontalScrollView mButtonScrollSlide; // 滚动进度
    private int manualPadding;                // 手动游标内边距，兼容backgound

    OnTabPagerChangeListener onTabPagerChangeListener;


    public void setOnTabPagerChangeListener(OnTabPagerChangeListener onTabPagerChangeListener) {
        this.onTabPagerChangeListener = onTabPagerChangeListener;
    }

    public interface OnTabPagerChangeListener {
        void onPageSelected(int position);
    }

    public TabPagerView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public TabPagerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        mMaxHolCount = 3;
        manualPadding = 0;
        mSlideHeight = (int) (getResources().getDisplayMetrics().density * 28);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.tab_pager_layout, this);
        mViewPager = (ViewPager) findViewById(R.id.table_page);
        mActivity = (FragmentActivity) context;
        mFragmentList = new ArrayList<Fragment>();
        mButtonTitle = new ArrayList<TextView>();
        mButtonScrollSlide = (HorizontalScrollView) findViewById(R.id.table_button_scroll);
        mSlide = (ImageView) findViewById(R.id.table_slide);
        mButtonLinear = (LinearLayout) findViewById(R.id.table_button_text);

    }

    @Override
    protected void onFinishInflate() {
        // TODO Auto-generated method stub
        super.onFinishInflate();

    }


    /**
     * 添加子页面
     *
     * @param f     子页面Fragment,V4包的
     * @param title 标题
     */
    public void addOnePage(Fragment f, String title) {
        mFragmentList.add(f);
        TextView ntv = new TextView(mActivity);
        ntv.setTextSize(14);
        ntv.setTextColor(getResources().getColor(R.color.tab_txt_n));
        ntv.setGravity(Gravity.CENTER);
        ntv.setText(title);
        ntv.setOnClickListener(this);
        mButtonTitle.add(ntv);
        RefreshTableButton();
        mPageAdapter.notifyDataSetChanged();
    }


    /**
     * 添加所有的 fragment
     * @param activity
     * @param tabDatas
     * @param fragments
     */
    public void addAllPage(FragmentActivity activity, List<String> tabDatas, List<Fragment> fragments) {
        mFragmentList.clear();
        for (int i = 0; i < tabDatas.size(); i++) {
            mFragmentList.add(fragments.get(i));
            TextView ntv = new TextView(mActivity);
            ntv.setTextSize(15);
            ntv.setTextColor(getResources().getColor(R.color.tab_txt_n));
            ntv.setGravity(Gravity.CENTER);
            ntv.setText(tabDatas.get(i));
            ntv.setOnClickListener(this);
            mButtonTitle.add(ntv);
            RefreshTableButton();
        }

        showTabTxtColor(0);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setOnPageChangeListener(this);

        mPageAdapter = new PagerAdapter(activity.getSupportFragmentManager(), tabDatas.size());
        mViewPager.setAdapter(mPageAdapter);



    }


    public void setMaxTitle(int count) {
        mMaxHolCount = count;
    }

    /**
     * 删除子页面
     *
     * @param index
     */
    public void RemoveOnePage(int index) {
        if (index >= mFragmentList.size())
            return;
        mFragmentList.remove(index);
        mButtonTitle.remove(index);
        RefreshTableButton();
        mPageAdapter.notifyDataSetChanged();
    }

    /**
     * 私有函数，完全是给RefreshTableButton准备的，只是为了可重用
     */
    private void RefreshButton() {
        mButtonLinear.removeAllViews();
        if (mFragmentList.size() == 0) {
            mSlide.setVisibility(View.INVISIBLE);
        } else if (mFragmentList.size() <= mMaxHolCount) {

            mSlideWidth = mSlideWidthSpace / mFragmentList.size();
            manualPadding = 0;//mSlideWidth / mMaxHolCount;
            //mSlideDistance = mSlideWidthSpace - width;
            RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams) mSlide.getLayoutParams();
            relativeParams.leftMargin = manualPadding;
            relativeParams.width = mSlideWidth - 2 * manualPadding;
            //relativeParams.height = mSlideHeight;
            mSlide.setVisibility(View.VISIBLE);
            mSlide.setLayoutParams(relativeParams);
            LayoutParams linearParams = new LayoutParams(mSlideWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
            for (TextView tv : mButtonTitle) {
                mButtonLinear.addView(tv, linearParams);
            }
        } else {
            mSlideWidth = mSlideWidthScroll;
            manualPadding = 0;//mSlideWidth / mMaxHolCount;
            RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams) mSlide.getLayoutParams();
            mSlide.setVisibility(View.VISIBLE);
            relativeParams.leftMargin = manualPadding;
            relativeParams.width = mSlideWidth - 2 * manualPadding;
            // relativeParams.height = mSlideHeight;
            mSlide.setLayoutParams(relativeParams);
            LayoutParams linearParams = new LayoutParams(mSlideWidthScroll,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            for (TextView tv : mButtonTitle) {
                mButtonLinear.addView(tv, linearParams);
            }
        }
    }

    /**
     * 根据List<Fragment> mFragmentList缓存，刷新按钮界面，包括计算slide宽度等
     */
    private void RefreshTableButton() {
        if (mSlideWidthSpace <= 0) {
            // 如果未初始化界面参数，通过回调获取
           /* final View v = this;
            ViewTreeObserver vto = getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {

                }
            });*/


            mSlideWidthSpace = getResources().getDisplayMetrics().widthPixels;
            mSlideWidthScroll = mSlideWidthSpace / mMaxHolCount;
            RefreshButton();
        } else {
            RefreshButton();
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub
        // just 动态滑动滑块
        RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams) mSlide.getLayoutParams();
        float x = (arg1 + arg0) * mSlideWidth;
        relativeParams.leftMargin = (int) x;
        if (mButtonScrollSlide.getScrollX() > relativeParams.leftMargin) {
            // 超左边距
            mButtonScrollSlide.scrollTo(relativeParams.leftMargin, 0);
        }
        if (relativeParams.leftMargin + mSlideWidth > mSlideWidthSpace + mButtonScrollSlide.getScrollX()) {
            // 超右边距
            mButtonScrollSlide.scrollTo(relativeParams.leftMargin + mSlideWidth - mSlideWidthSpace, 0);
        }
        relativeParams.leftMargin += manualPadding;
        //Log.e("sun",String.format("leftMargin=%s arg0=%s arg1=%s arg2=%s index=%s x=%s", relativeParams.leftMargin,arg0,arg1,arg2,mViewPager.getCurrentItem(),x));
        mSlide.setLayoutParams(relativeParams);
    }

    @Override
    public void onPageSelected(int arg0) {
        // TODO Auto-generated method stub
        showTabTxtColor(arg0);

        if (onTabPagerChangeListener != null) {
            onTabPagerChangeListener.onPageSelected(arg0);
        }
    }


    /**
     * 显示tab颜色
     *
     * @param posi
     */
    private void showTabTxtColor(int posi) {
        for (int i = 0; i < mButtonTitle.size(); i++) {
            if (i == posi) {
                mButtonTitle.get(i).setTextColor(getResources().getColor(R.color.tab_txt_p));
            } else {
                mButtonTitle.get(i).setTextColor(getResources().getColor(R.color.tab_txt_n));
            }

        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        for (int i = 0; i < mButtonTitle.size(); i++) {
            if (v == mButtonTitle.get(i)) {
                mViewPager.setCurrentItem(i);
            }
        }
    }

    public class PagerAdapter extends FragmentStatePagerAdapter {
        int mNumOfTabs;

        public PagerAdapter(FragmentManager fm, int NumOfTabs) {
            super(fm);
            this.mNumOfTabs = NumOfTabs;
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mNumOfTabs;
        }
    }


}
